# coding:utf-8

from databaseHandler import *
from datetime import datetime
from .articleModel import *
from .nodeModel import *

# 用户的数据库模型


class User(db.Entity):
    nickName = Required(str, unique=True)  # 昵称
    userIntroduction = Optional(str)  # 用户介绍
    passWord = Required(str)  # 密码
    tel = Required(str)  # 手机号码,用户找回密码,在注册时候需要验证
    Email = Required(str, unique=True)  # 邮箱
    regTime = Required(datetime)  # 注册时间,由系统自动在注册时候自动生成
    avatar = Required(str, unique=True)  # 用户头像
    articles = Set('Article')  # 用户发表的帖子
    favoritedArticles = Set('Article')  # 用户收藏的文章
    follower = Set('User')  # 关注User的用户
    followedUser = Set('User', reverse='follower')  # 被User关注的用户
    replys = Set('Reply')  # 用户的回复
    likedReplys = Set('Reply')  # 点赞的回复
    favoritedReplys = Set('Reply')  # 收藏的回复
    applicantNodes = Set('Node', reverse='nodeApplicant')  # 申请建立的节点
    managedNodes = Set('Node', reverse='nodeManager')  # 管理的节点
    favoritedNodes = Set('Node')  # 收藏的节点


# 新建用户
@db_session
def newUser(nickName, passWord, tel, Email):
    if User(nickName=nickName, passWord=passWord, tel=tel, Email=Email, avatar='noimage', regTime=datetime.now()):
        return True
    else:
        return False

# 通过给定的电邮地址查找用户


@db_session
def getUserByEmail(Email):
    user = User.get(Email=Email)
    return user

# 通过给定的昵称查找用户


@db_session
def getUserByNickname(nickName):
    user = User.get(nickName=nickName)
    return user

# 判断电邮地址是否已被注册


@db_session
def checkUserByEmail(Email):
    return User.exists(Email=Email)

# 判断昵称是否已被使用


@db_session
def checkUserByNickName(nickName):
    return User.exists(nickName=nickName)

# 判断手机号码是否已被注册


@db_session
def checkUserByTel(tel):
    return User.exists(tel=tel)


# 修改用户信息
@db_session
def changeUserPassword(userId, nickName, userIntroduction, passWord, tel, Email):
    user = User.get(id=userId)
    if checkUserByNickName(nickName) is not True:
        return "昵称已被占用"
    elif checkUserByTel(tel) is not True:
        return "手机号码已被占用"
    elif checkUserByEmail(Email) is not True:
        return "电邮地址已被占用"
    else:
        user.set(
            nickName=nickName,
            userIntroduction=userIntroduction,
            passWord=passWord,
            tel=tel,
            Email=Email
        )
        db.commit()
        return True
